import $ from './library/jquery.js';
import cookie from './library/cookie.js';
// 通过search 获得商品id
let id = location.search.split('=')[1];
var num = 1;

$.ajax({
    type: "get",
    url: "../../interface/getItem.php",
    data: { id: id },
    dataType: "json"
}).then(function(res) {
    let picture = JSON.parse(res.picture);
    console.log(picture);
    let temp = `
    <img src="../${picture[0].src}">

    `;
    console.log(picture[0].src);
    let money3 = `
    <div>${res.title} 黑色款
    <span>${res.price}元<del>${res.dell}</del></span>
    </div>
    <div>总计：${res.price}元</div>
    `;
    $('.details').html(res.details);
    $('.title_').html(res.title);
    $('.money').html(res.price);
    $('.php').html(temp);
    $('.money3').html(money3);
    console.log(money3)

    $('.addItem').on('click', function() {
        console.log(cookie);
        addItem(res.id, res.price, 1)

    })
}).catch(function(xhr) {
    console.log(xhr.status)
});

function addItem(id, price, num) {
    let shop = cookie.get('shop');

    let product = {
        id,
        price,
        num
    };

    if (shop) {
        shop = JSON.parse(shop);

        if (shop.some(el => el.id === id)) {
            let _index = shop.findIndex(elm => elm.id === id);
            let count = parseInt(shop[_index].num);
            count += parseInt(num);
            shop[_index].num = count;
        } else {
            shop.push(product);
        }
    } else {
        shop = [];
        shop.push(product);
    }
    console.log(shop);
    cookie.set('shop', JSON.stringify(shop), 1);
}